<template>
  <div>
    <Screen v-if="screening" />
    <Editor v-else />
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue"
import { storeToRefs } from "pinia"
import { useSnapshotStore } from "./store/snapshot"
import { useMainStore } from "./store/main"
import { useScreenStore } from "./store/screen"
import { deleteDiscardedDB } from '@/utils/database'
import { LOCALSTORAGE_KEY_DISCARDED_DB } from './configs/storage'

import Editor from "@/views/Editor/index.vue"
import Screen from "@/views/Screen/index.vue"

const snapshotStore = useSnapshotStore()
const mainStore = useMainStore()
const { databaseId } = storeToRefs(mainStore)
const { screening } = storeToRefs(useScreenStore())

onMounted(async () => {
  // 删除失效过期的数据库
  await deleteDiscardedDB()
  // 初始化数据库
  snapshotStore.initSnapshotDatabase()
  // 设置可利用的字体
  mainStore.setAvailableFonts()
})

/**
 * 当文档或一个子资源正在被卸载时，触发 unload事件。
 * 应用注销时向 localStorage 中记录下本次 indexedDB 的数据库ID，用于之后清除数据库
 */
window.addEventListener('unload', () => {
  const discardedDB = localStorage.getItem(LOCALSTORAGE_KEY_DISCARDED_DB)
  const discardedDBList: string[] = discardedDB ? JSON.parse(discardedDB) : []
  discardedDBList.push(databaseId.value)
  const newDiscardedDB = JSON.stringify(discardedDBList)
  localStorage.setItem(LOCALSTORAGE_KEY_DISCARDED_DB, newDiscardedDB)
})
</script>

<style lang="scss">
#app {
  height: 100%;
}
</style>